import axios, {
  type InternalAxiosRequestConfig,
  type AxiosError,
  type AxiosResponse,
} from "axios";
import {
  type RequestMateConfig,
  type ApiResponse,
  Code,
  type RequestConfig,
} from "./model";

/**
 * 创建请求单例
 */
const instance = axios.create({
  baseURL: import.meta.env.VITE_GLOB_API_URL,
  timeout: 10000,
  headers: {
    "Content-Type": "application/json",
  },
});

/**
 * 请求拦截器
 */
instance.interceptors.request.use(
  (config: InternalAxiosRequestConfig & RequestMateConfig) => {
    const { mate } = config;
    const { needToken = true } = mate || {};

    if (needToken) {
      // 读取token 并按照后端放入请求中
    }
    return config;
  },
  (error: AxiosError) => {
    return Promise.reject(error);
  }
);

/**
 * 响应拦截器
 */
instance.interceptors.response.use(
  (response: AxiosResponse) => {
    const config = response.config as InternalAxiosRequestConfig &
      RequestMateConfig;
    // 文件流
    if (response.config.responseType === "blob") {
      return response;
    }
    // 数据响应处理
    const { data } = response;
    const { code, msg } = data as ApiResponse<any>;
    const { mate } = config;
    const { showTip = false } = mate || {};
    if (code == Code.NOT_LOGIN) {
      // 没有登陆
    }
    if (showTip) {
      //全局提示信息
      console.log(msg);
    }
    if (code == Code.ERROR) {
      return Promise.reject(data);
    }
    return data.data;
  },
  (error: AxiosError) => {
    if (error.code === "ERR_NETWORK") {
      // 网络请求错误
    }
    return Promise.reject(error);
  }
);

/**
 * 基础请求
 * @param config RequestConfig
 * @returns
 */
export function request<T = any>(config: RequestConfig): Promise<T> {
  return instance.request(config);
}

export default instance;
